<?php

namespace App\Http\Controllers;

use App\Models\Messages;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Validator;

class MessageController extends Controller
{
    public function store(Request $request)
    {
        // 检查IP提交限制
        $ip = $request->ip();
        $ipKey = 'message_submit_' . $ip;
        $submitCount = Cache::get($ipKey, 0);
        
        // 检查是否超过限制（同一IP一天最多3次）
        if ($submitCount >= 3) {
            return redirect()->back()
                ->withInput()
                ->with('error', '您今天的提交次数已达上限，请明天再试！');
        }

        // 验证表单数据
        $validator = Validator::make($request->all(), [
            'name' => 'required|max:255',
            'mobile' => 'required|regex:/^1[3-9]\d{9}$/',
            'content' => 'required|max:200',
            'captcha' => 'required|captcha',
        ], [
            'name.required' => '请输入姓名',
            'name.max' => '姓名不能超过255个字符',
            'mobile.required' => '请输入手机号',
            'mobile.regex' => '请输入正确的手机号格式',
            'content.required' => '请输入咨询内容',
            'content.max' => '内容不能超过200个字符',
            'captcha.required' => '请输入验证码',
            'captcha.captcha' => '验证码不正确',
        ]);

        // 如果验证失败，重定向回表单页面并显示错误信息
        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput()
                ->with('error', $validator->errors()->first());
        }

        // 验证是否勾选了咨询项目
        if (!$request->has('target') || !is_array($request->target) || empty($request->target)) {
            return redirect()->back()
                ->withInput()
                ->with('error', '请至少选择一项咨询内容');
        }

        try {
            // 创建消息记录
            $message = new Messages();
            $message->name = $request->name;
            $message->mobile = $request->mobile;
            $message->target = implode(',', $request->target); // 将多选项合并为逗号分隔的字符串
            $message->content = $request->content;
            $message->save();

            // 增加IP提交计数，并设置24小时后过期
            Cache::put($ipKey, $submitCount + 1, now()->addHours(24));

            // 返回成功消息
            return redirect()->back()->with('success', '您的留言已提交，我们将尽快联系您！');
        } catch (\Exception $e) {
            // 记录错误日志
            Log::error('留言提交失败: ' . $e->getMessage());
            
            // 返回错误消息
            return redirect()->back()
                ->withInput()
                ->with('error', '提交失败，请稍后重试！');
        }
    }
} 